const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const {auth} = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadPath = path.join(__dirname, '../../img');
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'writer_' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  fileFilter: function (req, file, cb) {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 
  }
});

router.get('/', async (req, res) => {
  try {
    // 如果请求所有作家（不分页），用于下拉选择
    if (req.query.all === 'true') {
      const [rows] = await pool.execute(
        'SELECT id, name FROM writer ORDER BY name'
      );
      return res.json({
        total: rows.length,
        writers: rows
      });
    }

    let page = parseInt(req.query.page) || 1;
    let pageSize = parseInt(req.query.pageSize) || 5;
    const searchQuery = req.query.search || '';

    if (page < 1) page = 1;
    if (pageSize < 1) pageSize = 5;

    let query = 'SELECT id, name, avatar_path FROM writer';
    let countQuery = 'SELECT COUNT(*) as count FROM writer';

    const queryParams = [];
    const countParams = [];

    if (searchQuery) {
      query += ' WHERE name LIKE ?';
      countQuery += ' WHERE name LIKE ?';
      queryParams.push(`%${searchQuery}%`);
      countParams.push(`%${searchQuery}%`);
    }

    query += ' ORDER BY id LIMIT ? OFFSET ?';
    queryParams.push(pageSize.toString(), ((page - 1) * pageSize).toString());

    const [countRows] = await pool.execute(countQuery, countParams);
    const total = countRows[0].count;

    const [rows] = await pool.execute(query, queryParams);

    res.json({
      total,
      writers: rows
    });
  } catch (error) {
    console.error('获取作家列表失败:', error);
    res.status(500).json({
      message: '获取作家列表失败',
      error: error.message
    });
  }
});

router.get('/random', async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT id, name, experience, avatar_path FROM writer ORDER BY RAND() LIMIT 1'
    );

    if (rows.length === 0) {
      return res.status(404).json({ message: '没有找到作家' });
    }

    res.json(rows[0]);
  } catch (error) {
    console.error('获取随机作家失败:', error);
    res.status(500).json({
      message: '获取随机作家失败',
      error: error.message
    });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const writerId = req.params.id;
    
    const [rows] = await pool.execute(
      'SELECT w.id, w.name, w.experience, w.avatar_path, w.user_id, w.created_at, u.username FROM writer w LEFT JOIN user u ON w.user_id = u.id WHERE w.id = ?',
      [writerId]
    );

    if (rows.length === 0) {
      return res.status(404).json({ message: '作家不存在' });
    }

    res.json(rows[0]);
  } catch (error) {
    console.error('获取作家详情失败:', error);
    res.status(500).json({
      message: '获取作家详情失败',
      error: error.message
    });
  }
});

router.post('/', auth, upload.single('avatar'), async (req, res) => {
  try {
    const { name, experience } = req.body;
    const userId = req.user.userId;

    if (!name) {
      return res.status(400).json({ message: '作家姓名不能为空' });
    }

    let avatarPath = null;
    if (req.file) {
      avatarPath = `/img/${req.file.filename}`;
    }

    const [result] = await pool.execute(
      'INSERT INTO writer (name, experience, avatar_path, user_id) VALUES (?, ?, ?, ?)',
      [name, experience || null, avatarPath, userId]
    );

    const writerId = result.insertId;
  
    const [rows] = await pool.execute(
      'SELECT id, name, experience, avatar_path, user_id, created_at FROM writer WHERE id = ?',
      [writerId]
    );

    res.status(201).json(rows[0]);
  } catch (error) {
    console.error('创建作家失败:', error);
    res.status(500).json({
      message: '创建作家失败',
      error: error.message
    });
  }
});

router.put('/:id', auth, upload.single('avatar'), async (req, res) => {
  try {
    const writerId = req.params.id;
    const { name, experience } = req.body;
    const userId = req.user.userId;
    const userRole = req.user.role;

    const [existingWriters] = await pool.execute(
      'SELECT user_id, avatar_path FROM writer WHERE id = ?',
      [writerId]
    );

    if (existingWriters.length === 0) {
      return res.status(404).json({ message: '作家不存在' });
    }

    if (userRole !== 1 && existingWriters[0].user_id !== userId) {
      return res.status(403).json({ message: '没有权限编辑此作家' });
    }

    if (!name) {
      return res.status(400).json({ message: '作家姓名不能为空' });
    }
    let avatarPath = existingWriters[0].avatar_path;
    if (req.file) {
      if (existingWriters[0].avatar_path) {
        const oldImagePath = path.join(__dirname, '../..', existingWriters[0].avatar_path);
        if (fs.existsSync(oldImagePath)) {
          fs.unlinkSync(oldImagePath);
        }
      }
      avatarPath = `/img/${req.file.filename}`;
    }

    await pool.execute(
      'UPDATE writer SET name = ?, experience = ?, avatar_path = ? WHERE id = ?',
      [name, experience || null, avatarPath, writerId]
    );

    const [rows] = await pool.execute(
      'SELECT id, name, experience, avatar_path, user_id, created_at FROM writer WHERE id = ?',
      [writerId]
    );

    res.json(rows[0]);
  } catch (error) {
    console.error('更新作家失败:', error);
    res.status(500).json({
      message: '更新作家失败',
      error: error.message
    });
  }
});

router.delete('/:id', auth, async (req, res) => {
  try {
    const writerId = req.params.id;
    const userId = req.user.userId;
    const userRole = req.user.role;
    const [existingWriters] = await pool.execute(
      'SELECT user_id, avatar_path FROM writer WHERE id = ?',
      [writerId]
    );

    if (existingWriters.length === 0) {
      return res.status(404).json({ message: '作家不存在' });
    }
    if (userRole !== 1) {
      return res.status(403).json({ message: '只有管理员可以删除作家' });
    }

    if (existingWriters[0].avatar_path) {
      const imagePath = path.join(__dirname, '../..', existingWriters[0].avatar_path);
      if (fs.existsSync(imagePath)) {
        fs.unlinkSync(imagePath);
      }
    }

    await pool.execute('DELETE FROM writer WHERE id = ?', [writerId]);

    res.json({ message: '作家删除成功' });
  } catch (error) {
    console.error('删除作家失败:', error);
    res.status(500).json({
      message: '删除作家失败',
      error: error.message
    });
  }
});

module.exports = router;
